var projectId =  this.getQueryString("projectId")||'88888888888';
var queryCount = 0; // 初始化标记
var windowIndex = 0; // 典型日

$(function(){
	getGasOutputDatePicker(); // 初始化气源出力
	getLineFlowDatePicker(); // 初始化网络潮流
	getLoadCurveDatePicker(); // 初始化负荷曲线
})

function selectLoadCurve(){
	getLoadCurveEchart();
}
function selectLineFlow(){
	getLineFlowEchart();
}
function selectGasOutput(){
	getGasOutputEchart();
}

function getLoadCurveEchart() {
	queryCount++;
	var startDate =  $('#loadStartDate').val(); 
	var endDate =  $('#loadEndDate').val(); 
	var loadNames =  $('#loadNames').val();
	if(JyyCommon.isEmpty(startDate) || JyyCommon.isEmpty(endDate)){
		if(queryCount >= 3) JyyMsgBox.alert({ title:"警告", message:"[时间]不可为空",type:"warning"}).on(function (e) {});
		return false;
	}
	if(loadNames.length == 0){
		if(queryCount >= 3) JyyMsgBox.alert({ title:"警告", message:"[负荷名称]不可为空",type:"warning"}).on(function (e) {});
		return false;
	}
	if(loadNames.length > 12){
		if(queryCount >= 3) JyyMsgBox.alert({ title:"警告", message:"[负荷名称]不可超过12个",type:"warning"}).on(function (e) {});
		return false;
	}
	JyyModelLoading.start("loadCurveEchartDiv");
	$.when(getEcahtData({projectId:projectId,startDate:startDate, endDate:endDate, loadNames:loadNames}, 
			"selectGasLoadCurveEchatData")).done(function(echatData){
		createEchat(echatData, 3);
		JyyModelLoading.end("loadCurveEchartDiv");
	});
}
function getLineFlowEchart() {
	var startDate =  $('#lineStartDate').val(); 
	var endDate =  $('#lineEndDate').val(); 
	var lineNames =  $('#lineNames').val();
	if(JyyCommon.isEmpty(startDate) || JyyCommon.isEmpty(endDate)){
		if(queryCount >= 3) JyyMsgBox.alert({ title:"警告", message:"[时间]不可为空",type:"warning"}).on(function (e) {});
		return false;
	}
	if(lineNames.length == 0){
		if(queryCount >= 3) JyyMsgBox.alert({ title:"警告", message:"[线路名称]不可为空",type:"warning"}).on(function (e) {});
		return false;
	}
	if(lineNames.length > 12){
		if(queryCount >= 3) JyyMsgBox.alert({ title:"警告", message:"[线路名称]不可超过12个",type:"warning"}).on(function (e) {});
		return false;
	}
	JyyModelLoading.start("lineFlowEchartDiv");
	$.when(getEcahtData({projectId:projectId,startDate:startDate, endDate:endDate, lineNames:lineNames}, 
			"selectGasLineFlowEchatData")).done(function(echatData){
		queryCount++;
		createEchat(echatData, 2);
		JyyModelLoading.end("lineFlowEchartDiv");
	});
}
function getGasOutputEchart() {
	var startDate =  $('#startDate').val(); 
	var endDate =  $('#endDate').val(); 
	var unitNames =  $('#unitNames').val();
	if(JyyCommon.isEmpty(startDate) || JyyCommon.isEmpty(endDate)){
		if(queryCount >= 3) JyyMsgBox.alert({ title:"警告", message:"[时间]不可为空",type:"warning"}).on(function (e) {});
		return false;
	}
	if(unitNames.length == 0){
		if(queryCount >= 3) JyyMsgBox.alert({ title:"警告", message:"[机组名称]不可为空",type:"warning"}).on(function (e) {});
		return false;
	}
	if(unitNames.length > 12){
		if(queryCount >= 3) JyyMsgBox.alert({ title:"警告", message:"[机组名称]不可超过12个",type:"warning"}).on(function (e) {});
		return false;
	}
	JyyModelLoading.start("gasOutputEchartDiv");
	$.when(getEcahtData({projectId:projectId,startDate:startDate, endDate:endDate,unitNames:unitNames}, 
			"selectGasOutputEchatData")).done(function(echatData){
		queryCount++;
		createEchat(echatData, 1);
		JyyModelLoading.end("gasOutputEchartDiv");
	});
}

function createEchat(echartData, code) {
	var id = "";
	var option = {};
	var	xAxisName = "";
	var yAxisName = "";
	var	csvName = "";
	if(code == 1) {
		id = "gasOutputEchart";
		xAxisName = "时间";
		yAxisName = "MW";
		csvName = "气源出力情况";
	} else if(code == 2) {
		id = "lineFlowEchart";
		xAxisName = "时间";
		yAxisName = "MW";
		csvName = "网络潮流情况";
	} else if(code == 3) {
		id = "loadCurveEchart";
		xAxisName = "时间";
		yAxisName = "MW";
		csvName = "燃气负荷曲线情况";
	}
	var xAxisData = echartData.xAxisData;
	var seriesData = [];
	for(var i = 0; i < echartData.seriesData.length;i++) {
		seriesData.push({
			name: echartData.seriesData[i].name,
			type: 'line',
		    data: echartData.seriesData[i].series
		});
	}
	option = {
	  	tooltip: {
	    	trigger: 'axis',
	    	axisPointer: {
	      		type: 'cross',
	      		label: {
	        		backgroundColor: '#6a7985'
	      		}
	    	},
	    	position: function(point, params, dom, rect, size) {
	        	//其中point为当前鼠标的位置，size中有两个属性：viewSize和contentSize，分别为外层div和tooltip提示框的大小
	            var x = point[0]; //
	            var y = point[1];
	            var viewWidth = size.viewSize[0];
	            var viewHeight = size.viewSize[1];
	            var boxWidth = size.contentSize[0];
	            var boxHeight = size.contentSize[1];
	            var posX = 0; //x坐标位置
	            var posY = 0; //y坐标位置

	            if (x < boxWidth) { //左边放不开
	            	posX = 5;
	            } else { //左边放的下
	                posX = x - boxWidth;
	            }
	            if (y < boxHeight) { //上边放不开
	                posY = 5;
	            } else { //上边放得下
	                posY = y - boxHeight;
	            }
	            return [posX, posY];
	    	}
	  	},
		toolbox: {
			show: true,
			right: 30,
		    itemSize: 20,
			itemGap: 12,
	        feature: {
	        	myTool: {
	        		show: true,
	        		title: "导出为Excel",
	        		icon: 'image://../images/excel.png',
	        		onclick: (o) => {
						var option = o.option;
						var dataSource = [];
						var dataType = "\uFEFF"; //解决乱码问题
						dataType += option.xAxis[0].name+",";  //添加表格的头
						if(option.series.length > 0) {
							for(var i = 0;i < option.series.length;i++) {
								dataType += option.series[i].name+","
							}
							dataType = dataType.substr(0, dataType.length-1)
						}
						dataType += '\n'; // 以上是导出的Excel文件头部

						for(var i = 0;i < option.xAxis[0].data.length;i++) {
							var arr = [];
							for(var j = 0;j < option.series.length+1;j++) {
								if(j == 0) {
									arr.push(" "+option.xAxis[0].data[i]);
								} else {
									arr.push(option.series[j-1].data[i]);
								}
							}
							dataSource.push(arr);
						}
						// 从dataSource中取出数据存入数据源（dataType）
						dataSource.map(item => dataType += `${item.join(',')}\n`); 
						// 使用Blob，获得二进制实例
						const csvData = new Blob([dataType], {
						    type: 'text/csv'
						});
						// 创建a标签
						const _a = document.createElement('a');
						_a.href = URL.createObjectURL(csvData);
						_a.target = '_blank';
						_a.download = csvName + `.csv`;
						document.body.appendChild(_a);
						_a.click();
						document.body.removeChild(_a);
                   	},
	        	},
	        	saveAsImage: {name:csvName,icon:"image://../images/downpic.png"}
	        }
	    },
	  	grid: {
	    	left: '3%',
	    	right: '4%',
	    	bottom: '15%',
	    	containLabel: true
	  	},
	  	xAxis: [{
	    	type: 'category',
	    	name: xAxisName,
	      	boundaryGap: false,
	      	data: xAxisData
	    }],
	  	yAxis: [{
	      	type: 'value',
	      	name: yAxisName
	    }],
	    dataZoom: [{
	        type: "inside",
	    	start: 0,
	    	end: 100
	    },{
	    	start: 0,
	    	end: 100
	    }],
		legend: {},
	  	series: seriesData
	};
	var chartDom = document.getElementById(id);
	var myChart = echarts.init(chartDom);
	myChart.clear();
	myChart.setOption(option);
	window.addEventListener("resize", () => {
		if(myChart){
			myChart.resize()
		}
	})
}

function getLoadNameDatas() {
	$.ajax({
		url: "../g/service/Sample/getGasLoadNameDatas",
		type:'POST',
		async:false,
		dataType: "json",
		data:JSON.stringify({ projectId : projectId }),
		contentType:"application/json",
        success:function(data){
			var content = '';
			var sel = '';
			$.each(data.loadname,function(i,n){
				if(i == 0) {
					sel = n.code;
				}
				content += "<option value='" + n.code + "'>"+ n.name +"</option>";
			});
			if(content != '') {
				$("#loadNames").html(content);
				$('#loadNames').selectpicker('val', sel);
				$('#loadNames').selectpicker('refresh');
			}
			getLoadCurveEchart();
        }
	});
}
function getLineNameDatas() {
	$.ajax({
		url: "../g/service/Sample/getGasLineNameDatas",
		type:'POST',
		async:false,
		dataType: "json",
		data:JSON.stringify({ projectId : projectId }),
		contentType:"application/json",
        success:function(data){
			var content = '';
			var sel = '';
			$.each(data.linename,function(i,n){
				if(i == 0) {
					sel = n.code;
				}
				content += "<option value='" + n.code + "'>"+ n.name +"</option>";
			});
			if(content != '') {
				$("#lineNames").html(content);
				$('#lineNames').selectpicker('val', sel);
				$('#lineNames').selectpicker('refresh');
			}
			getLineFlowEchart();
        }
	});
}
function getUnitNameDatas() {
	$.ajax({
		url: "../g/service/Sample/getGasUnitNameDatas",
		type:'POST',
		async:false,
		dataType: "json",
		data:JSON.stringify({ projectId : projectId }),
		contentType:"application/json",
        success:function(data){
			var content = '';
			var sel = '';
			$.each(data.unitname,function(i,n){
				if(i == 0) {
					sel = n.code;
				}
				content += "<option value='" + n.code + "'>"+ n.name +"</option>";
			});
			if(content != '') {
				$("#unitNames").html(content);
				$('#unitNames').selectpicker('val', sel);
				$('#unitNames').selectpicker('refresh');
			}
			getGasOutputEchart();
        }
	});
}

function getLoadCurveDatePicker(){
	$.ajax({
		url: "../g/service/Sample/getGasLoadCurveDate",
		type:'POST',
		cache:false,
		dataType: "json",
		data:JSON.stringify({ projectId : projectId }),
		contentType:"application/json",
        success:function(data){
        	if(!data.readonly){
    			$("#loadStartDate").datetimepicker({
    				format : 'yyyy-mm-dd', // 展现格式
    				autoclose : true, // 选择日期后关闭
    				language : 'zh-CN', //显示语言为中文
    				minView : "2",
    				startDate : new Date(data.startDate),
    				endDate : new Date(data.endDate)
    			});
    			$("#loadEndDate").datetimepicker({
    				format : 'yyyy-mm-dd', // 展现格式
    				autoclose : true, // 选择日期后关闭
    				language : 'zh-CN', //显示语言为中文
    				minView : "2",
    				startDate : new Date(data.startDate),
    				endDate : new Date(data.endDate)
    			});
    			$('#loadStartDate').on('changeDate', function(ev){
    			    $('#loadEndDate').datetimepicker('setStartDate', ev.date);
    			    var d = $('#loadEndDate').val();
    			    if (d) {
    			        var date = new Date(d.replace(/-/g, '/'));
    			        if(date != 'Invalid Date' && date < ev.date){
    			            $('#loadEndDate').datetimepicker('setDate', ev.date)
    			        }
    			    }
    			});
    			$("#loadStartDate").datetimepicker("setDate", new Date(data.startDate));
    			$("#loadEndDate").datetimepicker("setDate", new Date(data.startDate));
        	} else { // 禁用日期控件
    			$("#loadStartDate").datetimepicker({
    				format : 'yyyy-mm-dd', // 展现格式
    				autoclose : true, // 选择日期后关闭
    				language : 'zh-CN', //显示语言为中文
    				minView : "2",
    				startDate : new Date(),
    				endDate : new Date()-1000*60*60*24
    			});
    			$("#loadEndDate").datetimepicker({
    				format : 'yyyy-mm-dd', // 展现格式
    				autoclose : true, // 选择日期后关闭
    				language : 'zh-CN', //显示语言为中文
    				minView : "2",
    				startDate : new Date(),
    				endDate : new Date()-1000*60*60*24
    			});
    			if(queryCount >= 3) JyyMsgBox.alert({ title:"警告", message:"暂无相关数据",type:"warning"}).on(function (e) {});
        	}
        	getLoadNameDatas(); // 获取负荷名称下拉框
        }
	});
}
function getLineFlowDatePicker(){
	$.ajax({
		url: "../g/service/Sample/getNetWorkFlowDate",
		type:'POST',
		cache:false,
		dataType: "json",
		data:JSON.stringify({ projectId : projectId }),
		contentType:"application/json",
        success:function(data){
        	if(!data.readonly){
    			$("#lineStartDate").datetimepicker({
    				format : 'yyyy-mm-dd', // 展现格式
    				autoclose : true, // 选择日期后关闭
    				language : 'zh-CN', //显示语言为中文
    				minView : "2",
    				startDate : new Date(data.startDate),
    				endDate : new Date(data.endDate)
    			});
    			$("#lineEndDate").datetimepicker({
    				format : 'yyyy-mm-dd', // 展现格式
    				autoclose : true, // 选择日期后关闭
    				language : 'zh-CN', //显示语言为中文
    				minView : "2",
    				startDate : new Date(data.startDate),
    				endDate : new Date(data.endDate)
    			});
    			$('#lineStartDate').on('changeDate', function(ev){
    			    $('#lineEndDate').datetimepicker('setStartDate', ev.date);
    			    var d = $('#lineEndDate').val();
    			    if (d) {
    			        var date = new Date(d.replace(/-/g, '/'));
    			        if(date != 'Invalid Date' && date < ev.date){
    			            $('#lineEndDate').datetimepicker('setDate', ev.date)
    			        }
    			    }
    			});
    			$("#lineStartDate").datetimepicker("setDate", new Date(data.startDate));
    			$("#lineEndDate").datetimepicker("setDate", new Date(data.startDate));
        	} else { // 禁用日期控件
    			$("#lineStartDate").datetimepicker({
    				format : 'yyyy-mm-dd', // 展现格式
    				autoclose : true, // 选择日期后关闭
    				language : 'zh-CN', //显示语言为中文
    				minView : "2",
    				startDate : new Date(),
    				endDate : new Date()-1000*60*60*24
    			});
    			$("#lineEndDate").datetimepicker({
    				format : 'yyyy-mm-dd', // 展现格式
    				autoclose : true, // 选择日期后关闭
    				language : 'zh-CN', //显示语言为中文
    				minView : "2",
    				startDate : new Date(),
    				endDate : new Date()-1000*60*60*24
    			});
    			if(queryCount >= 3) JyyMsgBox.alert({ title:"警告", message:"暂无相关数据",type:"warning"}).on(function (e) {});
        	}
        	getLineNameDatas(); // 获取线路名称下拉框
        }
	});
}
function getGasOutputDatePicker(){
	$.ajax({
		url: "../g/service/Sample/getGasOutputDate",
		type:'POST',
		cache:false,
		dataType: "json",
		data:JSON.stringify({ projectId : projectId }),
		contentType:"application/json",
        success:function(data){
        	if(!data.readonly){
    			$("#startDate").datetimepicker({
    				format : 'yyyy-mm-dd', // 展现格式
    				autoclose : true, // 选择日期后关闭
    				language : 'zh-CN', //显示语言为中文
    				minView : "2",
    				startDate : new Date(data.startDate),
    				endDate : new Date(data.endDate)
    			});
    			$("#endDate").datetimepicker({
    				format : 'yyyy-mm-dd', // 展现格式
    				autoclose : true, // 选择日期后关闭
    				language : 'zh-CN', //显示语言为中文
    				minView : "2",
    				startDate : new Date(data.startDate),
    				endDate : new Date(data.endDate)
    			});
    			$('#startDate').on('changeDate', function(ev){
    			    $('#endDate').datetimepicker('setStartDate', ev.date);
    			    var d = $('#endDate').val();
    			    if (d) {
    			        var date = new Date(d.replace(/-/g, '/'));
    			        if(date != 'Invalid Date' && date < ev.date){
    			            $('#endDate').datetimepicker('setDate', ev.date)
    			        }
    			    }
    			});
    			$("#startDate").datetimepicker("setDate", new Date(data.startDate));
    			$("#endDate").datetimepicker("setDate", new Date(data.startDate));
        	} else { // 禁用日期控件
    			$("#startDate").datetimepicker({
    				format : 'yyyy-mm-dd', // 展现格式
    				autoclose : true, // 选择日期后关闭
    				language : 'zh-CN', //显示语言为中文
    				minView : "2",
    				startDate : new Date(),
    				endDate : new Date()-1000*60*60*24
    			});
    			$("#endDate").datetimepicker({
    				format : 'yyyy-mm-dd', // 展现格式
    				autoclose : true, // 选择日期后关闭
    				language : 'zh-CN', //显示语言为中文
    				minView : "2",
    				startDate : new Date(),
    				endDate : new Date()-1000*60*60*24
    			});
    			if(queryCount >= 3) JyyMsgBox.alert({ title:"警告", message:"暂无相关数据",type:"warning"}).on(function (e) {});
        	}
        	getUnitNameDatas(); // 获取机组类型下拉框
        }
	});
}
function openTypicalDay(e) {
	$("#tpyicalDayDiv").show();
	dragPanelMove(".window_top_title", "#tpyicalDayDiv");
	windowIndex = e;

	$.ajax({
		url: "../g/service/Sample/getTpyicalDay",
		type:'POST',
		cache:false,
		dataType: "json",
		data:JSON.stringify({ projectId : projectId }),
		contentType:"application/json",
        success:function(data){
			var content = "";
			$.each(data.days,function(i,n){
				content += "<div class='window_option_div'>"+ n +"</div>";
			});
			$(".window_body").html(content);
			$(".window_option_div").click(function(){
				$(".window_option_div").each(function(e){
					$(this).removeClass("window_checked_option_div");
				});
				$(this).addClass("window_checked_option_div");
			});
		}
	});
}
function closeWindow() {
	$("#tpyicalDayDiv").hide();
}
function dragPanelMove(titleDiv, mainWinDiv) {
    $(titleDiv).mousedown(function (e) {
        var isMove = true;
        var div_x = e.pageX - $(mainWinDiv).offset().left;
        var div_y = e.pageY - $(mainWinDiv).offset().top;
        $(document).mousemove(function (e) {
            if (isMove) {
                var obj = $(mainWinDiv);
                obj.css({"left": e.pageX - div_x, "top": e.pageY - div_y, "margin": "unset"});
            }
        }).mouseup(function () {
            isMove = false;
        });
    });
}
function selDate() {
	if($(".window_checked_option_div").text() == undefined) return;
	var day = $(".window_checked_option_div").text().split(" ")[1];
	if(windowIndex == 1) {
		$("#startDate").datetimepicker("setDate", new Date(day));
		$("#endDate").datetimepicker("setDate", new Date(day));
		getGasOutputEchart();
	} else if(windowIndex == 2) {
		$("#lineStartDate").datetimepicker("setDate", new Date(day));
		$("#lineEndDate").datetimepicker("setDate", new Date(day));
		getLineFlowEchart();
	} else if(windowIndex == 3) {
		$("#loadStartDate").datetimepicker("setDate", new Date(day));
		$("#loadEndDate").datetimepicker("setDate", new Date(day));
		getLoadCurveEchart();
	}
	closeWindow();
}

function getEcahtData(args, method){
	var res = $.ajax({
		url: "../g/service/Sample/"+method,
		type:'POST',
		cache:false,
		dataType: "json",
		data:args ? JSON.stringify(args) : null,
		contentType:"application/json",
        success:function(data){
			return data;
        }
	});
	return res;
}

function getQueryString (name){
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	return r ? unescape(r[2]) : null;
}